const {
  GraphQLObjectType,
  GraphQLString,
  GraphQLBoolean,
  GraphQLInt,
  GraphQLFloat,
  GraphQLList,
  GraphQLInputObjectType
} = require('graphql')

const Gra = require('graphql')

debugger;

const axios = require('axios')

const ResultType = new GraphQLObjectType({
  name: 'ResultType',
  fields: {
    ret: {
      type: GraphQLBoolean,
    },
    message: {
      type: GraphQLString
    }
  }
})

const RootMutationType = new GraphQLObjectType({
  name: 'RootMutationType',
  fields: {
    create: {
      type: ResultType,
      args: {
        title: {
          type: GraphQLString
        },
        genres: {
          type: GraphQLString
        },
        rating: {
          type: new GraphQLInputObjectType({
            name: 'aa',
            fields: {
              hello: {
                type: GraphQLString 
              }
            }
          })
        },
        theater: {
          type: new GraphQLList(GraphQLInt)
        }
      },
      async resolve(obj, args) {
        await axios.post('http://localhost:9000/subjects', {
          ...args
        }).then(result => {
          return {
            ret: true,
            message: 'success'
          }
        }).catch(error => {
          return {
            ret: false,
            message: 'fail'
          }
        })
      }
    },

    update: {
      type: ResultType,
      args: {
        id: {
          type: GraphQLInt
        },
        title: {
          type: GraphQLString
        },
        genres: {
          type: GraphQLString
        },
        rating: {
          type: new GraphQLInputObjectType({
            name: 'bb',
            fields: {
              hello: {
                type: GraphQLString 
              }
            }
          })
        },
        theater: {
          type: new GraphQLList(GraphQLInt)
        }
      },
      async resolve(obj, args) {
        let result = await new Promise((resolve, reject) => {
          axios.patch(`http://localhost:9000/subjects/${args.id}`, {
            ...args
          }).then(result => {
            resolve({
              ret: true,
              message: 'success'
            })
          }).catch(error => {
            reject({
              ret: false,
              message: 'fail'
            })
          })
        })

        return result
      }
    },

    delete: {
      type: ResultType,
      args: {
        id: {
          type: GraphQLInt
        }
      },
      async resolve(obj, args) {
        let result = await new Promise((resolve, reject) => {
          axios.delete(`http://localhost:9000/subjects/${args.id}`)
          .then(result => {
            resolve({
              ret: true,
              message: 'success'
            })
          })
          .catch(error => {
            reject({
              ret: false,
              message: 'fail'
            })
          })
        })
        return result
      }
    }
  }
})

module.exports = RootMutationType